package com.flca.frw.zk.comp;

import java.util.Collection;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Button;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Window;

import com.flca.frw.zk.helper.ListboxHelper;
import com.flca.frw.zk.util.IListboxProvider;

public class OneToManyCtrl extends Window {

	private static final long serialVersionUID = -3826597789415472882L;

	private Collection<Object> items;
	
	private IListboxProvider provider;

	private SelectWindowCtrl selectCtrl;

	protected void updateView(Collection<Object> aItems, String aPropertyNames) 
	{
		items = aItems;
		Listbox listbox = (Listbox) getFellow("idItems");
		new ListboxHelper().fillListbox(listbox, aItems, aPropertyNames);
	}
	
	@SuppressWarnings("unchecked")
	public void updateView(Object aObject) 
	{
		if (aObject != null) {
			if (aObject instanceof Collection<?>) {
				items = (Collection<Object>) aObject;
				Listbox listbox = (Listbox) getFellow("idItems");
				new ListboxHelper().fillListbox(listbox, items, getPropertyNames());
			}
		} 
	}

	public Collection<?> getItems() {
		return items;
	}


	public void setItems(Collection<Object> items) {
		this.items = items;
	}

	public IListboxProvider getProvider() {
		return provider;
	}

	public void setProvider(IListboxProvider provider) {
		this.provider = provider;
	}

	public void onAdd() 
	{
		selectCtrl = (SelectWindowCtrl) Executions.createComponents("/comp/SelectWindow.zul", null, null);
		selectCtrl.addEventListener(eventName(), new SelectWinEventlistener());
		selectCtrl.setup(provider, eventName());
		try {
			selectCtrl.doModal();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	public void onEdit() {
		
	}

	public void onDel() {
		
	}
	
	public void onSelect() 
	{
		Button btn = (Button) getFellow("btnDel");
		btn.setDisabled(false);
	}	
	
//	private String getLabelNames() 
//	{
//		if (provider != null) {
//			return provider.getLabelNames();
//		} else {
//			return null;
//		}
//	}

	private String getPropertyNames() 
	{
		if (provider != null) {
			return provider.getPropertyNames();
		} else {
			return null;
		}
	}

	private void handleSelectWinEvent(Object aObject)
	{
		selectCtrl.detach();

		if (aObject != null) {
			items.add(aObject);
			updateView(items, getPropertyNames());
		}
		
	}
	
	
	class SelectWinEventlistener implements EventListener
	{
		public void onEvent(Event event) throws Exception {
			handleSelectWinEvent(event.getData());
		}
	}
	
	public String eventName() {
		if (provider != null) {
			return "onSelWin" + provider.getClass().getSimpleName();
		} else {
			return "onSelWin";
		}
	}	
}
